package info.sgu.ttdt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import info.androidhive.slidingmenu.R;
import info.sgu.ttdt.adapter.DatabaseHelper;
import info.sgu.ttdt.adapter.JsonUrl;
import info.sgu.ttdt.model.BookMark;
import info.sgu.ttdt.model.HocKy;
import info.sgu.ttdt.model.LichThi;
import info.sgu.ttdt.model.TaiKhoan;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.widget.AdapterView.OnItemSelectedListener;

public class LichThiFragment extends ListFragment {

	private ProgressDialog pDialog;

	// URL to get contacts JSON
	private static String url;

	// JSON Node names
	private static final String tag_mamonhoc = "mamonhoc";
	private static final String tag_tenmonhoc = "tenmonhoc";
	private static final String tag_ghepthi = "ghepthi";
	private static final String tag_tothi = "tothi";
	private static final String tag_soluong = "soluong";
	private static final String tag_ngaythi = "ngaythi";
	private static final String tag_giobatdau = "giobatdau";
	private static final String tag_sophut = "sophut";
	private static final String tag_phong = "phong";
	private static final String tag_hinhthucthi = "hinhthucthi";

	private static final String tag_tenhocky = "tenhocky";
	
	private static final String tag_masinhvien = "masinhvien";
	private static final String tag_tensinhvien = "tensinhvien";
	private static final String tag_lop = "lop";
	private static final String tag_nganh = "nganh";
	private static final String tag_khoa = "khoa";
	private static final String tag_hedaotao = "hedaotao";
	private static final String tag_khoahoc = "khoahoc";

	Spinner spinner;
	List<String> str;

	DatabaseHelper db;
	List<LichThi> datalist;

	// contacts JSONArray
	JSONArray data = null;
	ViewSwitcher viewSwitcher;

	// Hashmap for ListView
	ArrayList<HashMap<String, String>> dataList;

	Button btn_view;
	ImageButton btn_reload;
	ImageButton btn_bookmark;
	EditText txt_masv;;
	TextView txt_name;
	String masinhvien;
	String name;

	public LichThiFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_lichthi, container,
				false);
		SharedPreferences settings = getActivity()
				.getSharedPreferences("UserInfo", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("type", 4);
		editor.commit();
		spinner = (Spinner) rootView.findViewById(R.id.spinner2);
		viewSwitcher = (ViewSwitcher) rootView.findViewById(R.id.viewSwitcher2);
		txt_masv = (EditText) rootView.findViewById(R.id.editText_masv);
		txt_name = (TextView) rootView.findViewById(R.id.textView_name);
		OnItemSelectedListener SelectedListener = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View container,
					int position, long id) {
				Load(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		};
		spinner.setOnItemSelectedListener(SelectedListener);
		db = new DatabaseHelper(getActivity());
		datalist = new ArrayList<LichThi>();
		dataList = new ArrayList<HashMap<String, String>>();
		str = new ArrayList<String>();
		btn_view = (Button) rootView.findViewById(R.id.button_view);
		btn_view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				masinhvien = txt_masv.getText().toString();
				url = JsonUrl.getUrlLichThi(masinhvien);
				viewSwitcher.showNext();
				if (db.checkLichThi(masinhvien)) {
					if (db.checkTaiKhoan(masinhvien)) {
						TaiKhoan tk = db.getTaiKhoan(masinhvien);
						name = tk.getTensinhvien();
					}
					Load2(0);
				} else {
					// Calling async task to get json
					new GetContacts().execute();
				}
			}
		});
		btn_reload = (ImageButton) rootView.findViewById(R.id.button_reload2);
		btn_reload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				url = JsonUrl.getUrlLichThi(masinhvien);
				// Calling async task to get json
				new GetContacts().execute();
			}
		});
		btn_bookmark = (ImageButton) rootView.findViewById(R.id.imageButton1);
		btn_bookmark.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!db.checkBookmark(masinhvien, "Lịch thi"))
				{
					BookMark bm = new BookMark(masinhvien, name, "Lịch thi");
					db.createBookmark(bm);
					Toast.makeText(getActivity(), "Lưu Bookmark thành công", Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(getActivity(), "Bookmark đã tồn tại", Toast.LENGTH_SHORT).show();
			}
		});
		//SharedPreferences settings = getActivity().getSharedPreferences("UserInfo", 0);
		String masv = settings.getString("masinhvien", "").toString();
		if (!masv.equals("null") && !masv.isEmpty()) {
			masinhvien = settings.getString("masinhvien", "").toString();
			name = settings.getString("tensinhvien", "").toString();
			url = JsonUrl.getUrlLichThi(masinhvien);
			viewSwitcher.showNext();
			if (db.checkLichThi(masinhvien)) {
				Load2(0);
			} else {
				// Calling async task to get json
				new GetContacts().execute();
			}
		}

		return rootView;
	}

	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Vui lòng chờ...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			if(!db.checkTaiKhoan(masinhvien))
			{
				String url2 = JsonUrl.getUrlTaiKhoan(masinhvien);
				String jsonStr2 = sh.makeServiceCall(url2, ServiceHandler.GET);
				Log.d("Response: ", "> " + jsonStr2);
	
				if (jsonStr2 != null) {
					try {
						JSONObject jsonObj = new JSONObject(jsonStr2);
						JSONObject c = jsonObj.getJSONObject("taikhoan");
						if (c != null) {
							String masinhvien = c.getString(tag_masinhvien);
							String tensinhvien = c.getString(tag_tensinhvien);
							String lop = c.getString(tag_lop);
							String nganh = c.getString(tag_nganh);
							String khoa = c.getString(tag_khoa);
							String hedaotao = c.getString(tag_hedaotao);
							String khoahoc = c.getString(tag_khoahoc);
	
							TaiKhoan tk = new TaiKhoan(masinhvien, tensinhvien,
									lop, nganh, khoa, hedaotao, khoahoc, "");
							db.createTaiKhoan(tk);
						}
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					Log.e("ServiceHandler", "Couldn't get any data from the url");
				}
			}
			
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					JSONObject c4 = jsonObj.getJSONObject("taikhoan");
					name = c4.getString("tensinhvien");
					// Getting JSON Array node
					JSONArray data2 = jsonObj.getJSONArray("hocky");
					if (data2.length() > 0) {
						db.deleteLichThi(masinhvien);
						db.deleteHocKy(masinhvien, "thi");
					}
					for (int j = 0; j < data2.length(); j++) {
						JSONObject c2 = data2.getJSONObject(j);
						data = c2.getJSONArray("monthi");
						// looping through All Contacts
						for (int i = 0; i < data.length(); i++) {
							JSONObject c = data.getJSONObject(i);

							String mamonhoc = c.getString(tag_mamonhoc);
							String tenmonhoc = c.getString(tag_tenmonhoc);
							String ghepthi = c.getString(tag_ghepthi);
							String tothi = c.getString(tag_tothi);
							String soluong = c.getString(tag_soluong);
							String ngaythi = c.getString(tag_ngaythi);
							String giobatdau = c.getString(tag_giobatdau);
							String sophut = c.getString(tag_sophut);
							String phong = c.getString(tag_phong);
							String hinhthucthi = c.getString(tag_hinhthucthi);

							// tmp hashmap for single contact

							LichThi lt = new LichThi(mamonhoc, tenmonhoc,
									ghepthi, tothi, soluong, ngaythi,
									giobatdau, sophut, phong, hinhthucthi);
							db.createLichThi(lt, j, masinhvien);

						}
						String tenhocky = c2.getString(tag_tenhocky);
						HocKy hk = new HocKy(tenhocky);
						db.createHocKy(hk, masinhvien, "thi");

					}
					datalist = db.getAllLichThis(0, masinhvien);
					for (LichThi c : datalist) {
						HashMap<String, String> data = new HashMap<String, String>();
						data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
						data.put(tag_tenmonhoc,
								"Tên môn học: " + c.getTenmonhoc());
						data.put(tag_ghepthi, "Ghép thi: " + c.getGhepthi());
						data.put(tag_tothi, "Tổ Thi: " + c.getTothi());
						data.put(tag_soluong, "Số Lượng: " + c.getSoluong());
						data.put(tag_ngaythi, "Ngày Thi: " + c.getNgaythi());
						data.put(tag_giobatdau, "Giờ BĐ: " + c.getGiobatdau());
						data.put(tag_sophut, "Số phút: " + c.getSophut());
						data.put(tag_phong, "Phòng: " + c.getPhong());
						data.put(tag_hinhthucthi,
								"Hình thức thi: " + c.getHinhthucthi());
						// adding contact to contact list
						dataList.add(data);
					}
					List<HocKy> hks = db.getHocKys(masinhvien, "thi");
					for (HocKy hk : hks) {
						str.add(hk.getTenhocky());
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */
			ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
					R.layout.list_item3, new String[] { tag_mamonhoc,
							tag_tenmonhoc, tag_ghepthi, tag_tothi, tag_soluong,
							tag_ngaythi, tag_giobatdau, tag_sophut, tag_phong,
							tag_hinhthucthi }, new int[] { R.id.text1,
							R.id.text2, R.id.text3, R.id.text4, R.id.text5,
							R.id.text6, R.id.text7, R.id.text8, R.id.text9,
							R.id.text10 });
			setListAdapter(adapter);

			ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_spinner_item, str);
			spinner.setAdapter(adapter_state);
			txt_name.setText(masinhvien + " - " + name);
			int num = db.numberTaiKhoan();
			((MainActivity)getActivity()).NumberAccount(num, 4);
		}

	}

	private void Load(int position) {
		dataList.clear();
		datalist = db.getAllLichThis(position, masinhvien);
		for (LichThi c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
			data.put(tag_tenmonhoc, "Tên môn học: " + c.getTenmonhoc());
			data.put(tag_ghepthi, "Ghép thi: " + c.getGhepthi());
			data.put(tag_tothi, "Tổ Thi: " + c.getTothi());
			data.put(tag_soluong, "Số Lượng: " + c.getSoluong());
			data.put(tag_ngaythi, "Ngày Thi: " + c.getNgaythi());
			data.put(tag_giobatdau, "Giờ BĐ: " + c.getGiobatdau());
			data.put(tag_sophut, "Số phút: " + c.getSophut());
			data.put(tag_phong, "Phòng: " + c.getPhong());
			data.put(tag_hinhthucthi, "Hình thức thi: " + c.getHinhthucthi());
			// adding contact to contact list
			dataList.add(data);
		}

		ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
				R.layout.list_item3, new String[] { tag_mamonhoc,
						tag_tenmonhoc, tag_ghepthi, tag_tothi, tag_soluong,
						tag_ngaythi, tag_giobatdau, tag_sophut, tag_phong,
						tag_hinhthucthi }, new int[] { R.id.text1, R.id.text2,
						R.id.text3, R.id.text4, R.id.text5, R.id.text6,
						R.id.text7, R.id.text8, R.id.text9, R.id.text10 });
		setListAdapter(adapter);
	}

	private void Load2(int position) {
		dataList.clear();
		datalist = db.getAllLichThis(position, masinhvien);
		for (LichThi c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_mamonhoc, "Mã môn học: " + c.getMamonhoc());
			data.put(tag_tenmonhoc, "Tên môn học: " + c.getTenmonhoc());
			data.put(tag_ghepthi, "Ghép thi: " + c.getGhepthi());
			data.put(tag_tothi, "Tổ Thi: " + c.getTothi());
			data.put(tag_soluong, "Số Lượng: " + c.getSoluong());
			data.put(tag_ngaythi, "Ngày Thi: " + c.getNgaythi());
			data.put(tag_giobatdau, "Giờ BĐ: " + c.getGiobatdau());
			data.put(tag_sophut, "Số phút: " + c.getSophut());
			data.put(tag_phong, "Phòng: " + c.getPhong());
			data.put(tag_hinhthucthi, "Hình thức thi: " + c.getHinhthucthi());
			// adding contact to contact list
			dataList.add(data);
		}

		List<HocKy> hks = db.getHocKys(masinhvien, "thi");
		for (HocKy hk : hks) {
			str.add(hk.getTenhocky());
		}

		ListAdapter adapter = new SimpleAdapter(getActivity(), dataList,
				R.layout.list_item3, new String[] { tag_mamonhoc,
						tag_tenmonhoc, tag_ghepthi, tag_tothi, tag_soluong,
						tag_ngaythi, tag_giobatdau, tag_sophut, tag_phong,
						tag_hinhthucthi }, new int[] { R.id.text1, R.id.text2,
						R.id.text3, R.id.text4, R.id.text5, R.id.text6,
						R.id.text7, R.id.text8, R.id.text9, R.id.text10 });
		setListAdapter(adapter);

		ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item, str);
		spinner.setAdapter(adapter_state);
		txt_name.setText(masinhvien + " - " + name);
	}
}
